package com.th.common.utils.base64.picture;

import org.springframework.web.multipart.MultipartFile;


import java.io.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class BASE64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent; // 文件内容字节数组
    private final String header; // 文件头信息

    public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    /**
     * 将Base64字符串转成MultipartFile对象
     */
    public static MultipartFile base64ToMultipart(String base64) {
        String[] baseStrs = base64.split(",");
        String header = baseStrs[0];
        String content = baseStrs[1];

        Base64.Decoder decoder = Base64.getDecoder(); // 获取Base64解码器
        byte[] b = decoder.decode(content); // 解码Base64字符串

        return new BASE64DecodedMultipartFile(b, header);
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }
    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }
}
